package com.example.yrdev.ordering_system.Main_Menu;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.Database.RefundGoodTB;
import com.example.yrdev.ordering_system.Model.CustomViewHolder;
import com.example.yrdev.ordering_system.Model.Good;
import com.example.yrdev.ordering_system.Model.PurchaseReport;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.Utils.MIScanner;
import com.example.yrdev.ordering_system.homeOptions.PaymentDialog;

import java.util.ArrayList;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by luke on 9/30/16.
 */

public class MenuReturnGoodActivity extends CommonActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        showBackButton();

        setBarTitle("退货");

        initView();

        initNFCParam();

    }

     @InjectView(R.id.swipe_list)SwipeMenuListView swipeMenuListView;
    @InjectView(R.id.payMode)RadioGroup payMode;
    @InjectView(R.id.container_List)HorizontalScrollView containerView;
    @InjectView(R.id.noItem)LinearLayout noItem;

    PaymentDialog paymentDialog;
    ArrayList<PurchaseReport> arrayList;
    CustomAdapter customAdapter;
    PurchaseReport corresPondItem;
    Context context=MenuReturnGoodActivity.this;

    int paymode=3;

    public void initView(){

       setContentView(R.layout.return_good_activity_layout);
        ButterKnife.inject(this);


        payMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton selectedRadioButton=(RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());

                if (i==R.id.cash){

                   paymode=0;

                }else {

                    paymode=3;

                }

              reloadData();


                resetOptionView(selectedRadioButton);

            }

        });






    reloadData();

        swipeMenuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                corresPondItem=arrayList.get(i);

                GlobalFunction.printTextByTag("cardID:"+corresPondItem.getVipCardID());

                checkItem(corresPondItem);








            }
        });


    }
    private  void reloadData(){

    arrayList= PurchaseReport.getPurchaseReportBaseOnType(this,paymode);

        if (arrayList.size()>0){

        showContainerView(true);
            if (customAdapter==null){

                customAdapter=new CustomAdapter(this,arrayList);
                swipeMenuListView.setAdapter(customAdapter);

            }else {

                customAdapter.refresh(arrayList);

            }

        }else {

            showContainerView(false);

        }







    }
    private  void showContainerView(boolean stat){
        if (stat){

            containerView.setVisibility(View.VISIBLE);
            noItem.setVisibility(View.GONE);

        }else {
    GlobalFunction.printTextByTag("c");
            containerView.setVisibility(View.GONE);
            noItem.setVisibility(View.VISIBLE);

        }
    }
    public void resetOptionView(RadioButton selectedButton){
        for (int i=0;i<payMode.getChildCount();i++){
            RadioButton radioButton=(RadioButton)payMode.getChildAt(i);
            radioButton.setBackgroundColor(Color.parseColor("#b8d3ee"));
            radioButton.setTextColor(Color.parseColor("#c7c7c7"));

        }
        selectedButton.setBackgroundColor(Color.parseColor("#FF1B469A"));
        selectedButton.setTextColor(Color.parseColor("#FFFFFF"));
    }


    RefundGoodTB.Item refundItem;
    Integer refundCount=0;

    public int  checkRefundCount(PurchaseReport item){
        int count=0;

        refundItem =new RefundGoodTB.Item(item.getCommodityID());
        refundItem.setCard_ID(item.getVipCardID());
        refundItem.setItem_name(item.getCommodityName());
        refundItem.setItem_TicketID(item.getTicketID());
        refundItem.setItem_amount(item.getVolume());//退货数量
        refundItem.setItem_payMode(item.getPayMode());
        refundItem.setSaleCost(Double.valueOf(item.getSaleCost()));
        refundItem.setPrimeCost(item.getPrimeCost());
        refundItem.setDiscountRate(item.getDisCount());
        refundItem.setItem_purchDate(item.getDateTime());
        refundItem.setPurchaseVolume(item.getVolume());//购物数量
        refundItem.setEmployeeID(item.getEmployeeID());


        ArrayList<RefundGoodTB.Item> arrayList=RefundGoodTB.getRefundItemList(this,item);
        for (RefundGoodTB.Item tempItem:arrayList){


        count=count+tempItem.getItem_amount();
        }
        return count;


    }

    public boolean checkItem(PurchaseReport item){


        refundCount=checkRefundCount(item);

        if (refundCount<corresPondItem.getVolume()){//跟选中的产品比较
            if (corresPondItem.getVolume()>1){//如果产品数量>1

                showDialog();

            }else {
                switch (corresPondItem.getPayMode()){

                    case 3://刷卡退货

                    topUpCard();



                        break;

                    default://现金退货
                        handleRefundItem();



                        break;
                }



            }






        }


        if(refundCount.equals(corresPondItem.getVolume())){

            GlobalFunction.ToastAlert(this,"非常抱歉,你已退过此货");

        }





//        if (size==0){//此产品没有退过款,直接进行退货
//
//
//
//
//        }else {//曾经退过货
//
//
//        }
//
//




        return false;

    }
    private  void handleRefundItem(){

        Good respGood=Good.getCoresspondingGoodDetail(this,refundItem.getItem_ID());
        Integer storedNum=Integer.valueOf(respGood.getStoredNumber())+refundItem.getItem_amount();
        respGood.setStoredNumber(storedNum+"");
        Good.updateGoodStoreNumber(this,respGood);

        refundItem.setRestoredNum(storedNum);
        refundItem.setHttpDateTime(GlobalFunction.goodRequestHttpTime());

        GlobalFunction.printTextByTag(respGood+"");
        GlobalFunction.printTextByTag("insert:"+refundItem.getEmployeeID());
        RefundGoodTB.insertRecord(this,refundItem);
        GlobalFunction.ToastAlert(context,"退款成功");
       customAdapter.notifyDataSetChanged();

    }



    public void topUpCard(){
        if (paymentDialog==null){

            paymentDialog  =new PaymentDialog(MenuReturnGoodActivity.this,0,MenuReturnGoodActivity.this);
            paymentDialog.show();
            paymentDialog.startPurchaseMode();
            paymentDialog.changeTitle("退款");
//            paymentDialog.savePurchasePrice( GlobalFunction.convertToInt(refundItem.getTotalPrice()));

            paymentDialog.setPaymentValue(refundItem.getTotalPrice());
            reader.setOldCardID(refundItem.getCard_ID());
            reader.setOperate(1);
            reader.setAction(0);
            reader.setPurchaseMode(3);
            Double temp=refundItem.getTotalPrice()*100;
            reader.setReduceAmount(temp.intValue());
            paymentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    reader.reset();
                    paymentDialog=null;

                }
            });

            reader.setCallback(new MIScanner.Callback() {

                @Override
                public void showFixPurchaseCost(Double cost) {

                }

                @Override
                public void getCardInfo(Double reduceAmount,Double remain,Double currentBalance) {

                  paymentDialog.showOtherNominal(reduceAmount,remain,currentBalance);

                    closeDialog();



                }

                @Override
                public void getMICardNo(String cardNo,String ticketID) {

                    refundItem.setCard_ID(cardNo);
                    handleRefundItem();
                }
            });



        }
    }

    public  void showDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        LayoutInflater inflater=this.getLayoutInflater();
        View respView=inflater.inflate(R.layout.commodity_ask_amount_layout, null);
        // EditText editText=respView.findViewById()
        final EditText amount=(EditText)respView.findViewById(R.id.amount);
        amount.setOnTouchListener(editTextOnTouchListener());
        builder.setView(respView).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                int temp=Integer.valueOf(amount.getText().toString());

                if ( temp+refundCount>corresPondItem.getVolume() ){

                    GlobalFunction.ToastAlert(context,"请重新确认退货数量");


                }else {

                    refundItem.setItem_amount(temp);

                    switch (corresPondItem.getPayMode()){

                        case 3://刷卡退货

                            topUpCard();



                            break;

                        default://现金退货
                            handleRefundItem();


                            break;
                    }




                }


            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();

    }

    View.OnTouchListener editTextOnTouchListener(){
        View.OnTouchListener touchListener=new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                EditText editText=(EditText)view;
                editText.setCursorVisible(true);
                //  currentEditText=editText;

                return false;

            }
        };
        return touchListener;
    }



    public  void closeDialog(){

    new java.util.Timer().schedule(new TimerTask() {
        @Override
        public void run() {


             paymentDialog.dismiss();

            paymentDialog=null;

        }

    },1500);

    }
    //for reading MI CARD
    @Override
    protected void onResume() {
        super.onResume();


        try {

            reader.processIntent(mNfcAdapter,getIntent());
        }catch (Exception e){

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        try {

            reader.processIntent(mNfcAdapter, intent);
        }catch (Exception e){

        }


    }





   public static class CustomAdapter extends BaseAdapter{
       Context context;
       ArrayList <PurchaseReport>arrayList;

       public CustomAdapter(Context context,ArrayList<PurchaseReport> arrayList){
            this.context=context;
             this.arrayList=arrayList;

       }
       public void  refresh(ArrayList<PurchaseReport> arrayList){
           this.arrayList=arrayList;
           notifyDataSetChanged();
       }
       @Override
       public Object getItem(int i) {
           return arrayList.get(i);

       }

       @Override
       public long getItemId(int i) {
           return 0;
       }

       @Override
       public int getCount() {
           return arrayList.size();
       }

       @Override
       public View getView(int i, View view, ViewGroup viewGroup) {

           LayoutInflater layoutInflater=LayoutInflater.from(context);

           PurchaseReport goods=arrayList.get(i);

           if (view==null){

               view=layoutInflater.inflate(R.layout.return_good_table_row,null);
               CustomViewHolder viewHolder=new CustomViewHolder();
             viewHolder.setIndex((TextView)view.findViewById(R.id.index));
               viewHolder.setGoods_ticketID((TextView)view.findViewById(R.id.goods_ticketID));
               viewHolder.setGoods_code((TextView)view.findViewById(R.id.goods_code));
               viewHolder.setGoods_name((TextView)view.findViewById(R.id.goods_name));
               viewHolder.setGoods_purchDate((TextView)view.findViewById(R.id.goods_PurchaseDate));
               viewHolder.setGoods_amount((TextView)view.findViewById(R.id.goods_amount));
               viewHolder.setGood_RetailPrice((TextView)view.findViewById(R.id.goods_retail_price));
               viewHolder.setGood_totalPrice((TextView)view.findViewById(R.id.goods_totalPrice));
               viewHolder.setGood_refundCount((TextView)view.findViewById(R.id.goods_refundCount));
               view.setTag(viewHolder);

           //    GlobalFunction.printTextByTag("11"+goods.getItem_ID()+" "+goods.getItem_name());
           }

           CustomViewHolder viewHolder=(CustomViewHolder)view.getTag();
           viewHolder.getIndex().setText(i+1+"");
           viewHolder.getGoods_ticketID().setText(goods.getTicketID());
           viewHolder.getGoods_code().setText(goods.getCommodityID());
           viewHolder.getGoods_name().setText(goods.getCommodityName());
           viewHolder.getGoods_purchDate().setText(goods.getDateTime() );
           viewHolder.getGoods_amount().setText(String.valueOf(goods.getVolume()));
           viewHolder.getGood_RetailPrice().setText(String.valueOf(goods.getSaleCost())+"元");
           viewHolder.getGood_totalPrice().setText(String.valueOf(goods.getSaleCost())+"元");


            String payMod="";



           int temp=checkRefundCount(goods);
           if (temp==0){
               viewHolder.getGood_refundCount().setText("-");

           }else if(temp<goods.getVolume()){

               viewHolder.getGood_refundCount().setText(temp+"");

           }
           else {

               viewHolder.getGood_refundCount().setText("全部");
           }

           return view;
       }


       public int  checkRefundCount(PurchaseReport item){
           int count=0;
            RefundGoodTB.Item refundItem;

           refundItem =new RefundGoodTB.Item(item.getCommodityID());
           refundItem.setCard_ID(item.getVipCardID());
           refundItem.setItem_name(item.getCommodityName());
           refundItem.setItem_TicketID(item.getTicketID());
           refundItem.setItem_amount(item.getVolume());
           refundItem.setItem_payMode(item.getPayMode());
           refundItem.setSaleCost(Double.valueOf(item.getSaleCost()));
           refundItem.setItem_purchDate(item.getDateTime());

           ArrayList<RefundGoodTB.Item> arrayList=RefundGoodTB.getRefundItemList(context,item);
           for (RefundGoodTB.Item tempItem:arrayList){


               count=count+tempItem.getItem_amount();
           }
           return count;


       }


   }



}
